import requests
from bs4 import BeautifulSoup
import pickle
import os

# 文件路径
COOKIES_FILE = '../cookies/gkzy_session.pkl'


def login():
    """登录函数"""
    session = requests.Session()
    login_url = 'https://apin.gkzycc.cn/api/auth/login'

    # 准备登录数据（需要补充你的实际登录凭证）
    login_data = {
        'account': '19947079679',
        'autoLogin': 'true',
        'channel': 2,
        'code': '0',
        'password': '19947079679',
        'uuid': 'zyccn:CodeKey:eaeb3b62f822433a8eaaef6bf6a7a643'
    }

    login_data = {
        'account': '19947079679',
        'autoLogin': 'true',
        'channel': 2,
        'code': '0',
        'password': '19947079679',
        'uuid': 'zyccn:CodeKey:eaeb3b62f822433a8eaaef6bf6a7a643'
    }

    headers = {
        'Content-Type': 'application/json',
    }

    # 发送登录请求
    response = session.post(login_url, json=login_data, headers=headers)

    if response.status_code == 200:
        print("登录成功！")
        # 保存cookies到文件
        with open(COOKIES_FILE, 'wb') as f:
            pickle.dump(session.cookies, f)
        return session
    else:
        raise Exception(f"登录失败，状态码: {response.status_code}")


def get_session():
    """获取会话，优先使用保存的cookies"""
    if os.path.exists(COOKIES_FILE):
        try:
            # 尝试加载保存的cookies
            session = requests.Session()
            with open(COOKIES_FILE, 'rb') as f:
                session.cookies.update(pickle.load(f))

            # 测试cookies是否仍然有效
            test_url = 'https://wl.gkzycc.cn/data/collegeList'
            test_response = session.get(test_url)
            if test_response.status_code == 200:
                print("检测到有效cookies，无需重新登录")
                return session
        except Exception as e:
            print(f"加载cookies失败: {e}")

    # 如果没有保存的cookies或已失效，重新登录
    print("未检测到有效cookies，正在重新登录...")
    return login()


# 主程序
if __name__ == "__main__":
    try:
        # 获取会话（自动判断是否需要登录）
        session = get_session()

        # 爬取目标内容
        target_url = 'https://wl.gkzycc.cn/data/collegeList'
        headers = {
            'Content-Type': 'application/json',
        }

        response = session.get(target_url, headers=headers)
        response.encoding = response.apparent_encoding

        if response.status_code == 200:
            print("\n响应状态:", response.status_code)
            print("响应大小:", len(response.text), "字符")

            soup = BeautifulSoup(response.text, 'html.parser')
            page_title = soup.title.string if soup.title else "无标题"
            print("网页标题:", page_title)

            # 调试：打印部分内容
            print("\n页面片段:")
            print(response.text[:1000])  # 打印前1000个字符

        else:
            print(f"请求失败，状态码: {response.status_code}")

    except Exception as e:
        print(f"发生错误: {e}")
        # 如果出错，删除可能无效的cookies文件
        if os.path.exists(COOKIES_FILE):
            os.remove(COOKIES_FILE)
